package com.jy.appmarket.activity;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardListView;
import it.gmariotti.cardslib.library.view.PullToRefreshListView.RefreshingListener;

import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.jy.app.market.idata.card.CardApk;
import com.jy.app.market.idata.card.CardApkImages;
import com.jy.app.market.idata.data.Apk;
import com.jy.appmarket.R;
import com.jy.appmarket.cards.BaseUICard;
import com.jy.appmarket.cards.CardsUtils;
import com.jy.appmarket.cards.DownloadableUICard;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.SearchNetEngine;
import com.jy.appmarket.network.resultdata.PageResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.view.LoadingView;
import com.jy.appmarket.view.LoadingView.OnClickListener;
import com.umeng.analytics.MobclickAgent;

public class SearchResultActivity extends DownloadActivity implements NetTaskListener,
		RefreshingListener, OnEditorActionListener, View.OnClickListener {

	// private static final String TAG = "SearchResultActivity";
	public static final String EXTRA_KEY = "extra_search_key";

	private LoadingView mLoadingView;
	private CardListView mListview;
	private CardArrayAdapter mCardsAdapter;
	private ArrayList<Card> mCardsArray = new ArrayList<Card>();
	private NetTask mNetTask;

	private long mDataVersion;
	private int mPageIndex = 1;
	private String mkey;
	private boolean mIsFooterRefresh = false;

	private EditText mSearchEt;

	private ImageView mClearEditView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_result);
		getExtras();
		initTitle();
		initLoadingView();
		initListView();
		loadData(true);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}
	}

	private void getExtras() {
		if (getIntent() != null) {
			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				String key = extras.getString(EXTRA_KEY);
				mkey = Html.fromHtml(key).toString();
			}
		}
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setHomeButtonEnabled(false);

		actionBar.setCustomView(R.layout.cust_search_view);
		findViewById(R.id.back_bn).setOnClickListener(this);
		mClearEditView = findViewById(R.id.clear_edit_view);
		mClearEditView.setOnClickListener(this);
		mSearchEt = findViewById(R.id.search_ev);

		mSearchEt.setOnEditorActionListener(this);
		mSearchEt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				if (count > 0) {
					mClearEditView.setVisibility(View.VISIBLE);
				} else {
					mClearEditView.setVisibility(View.GONE);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.length() > 0) {
					mClearEditView.setVisibility(View.VISIBLE);
				} else {
					mClearEditView.setVisibility(View.GONE);
				}
			}
		});
		mSearchEt.setText(mkey);
		mSearchEt.setSelection(mkey.length());// 将光标追踪到内容的最后
	}

	private void initLoadingView() {
		mLoadingView = findViewById(R.id.loading_view_layout);
		mLoadingView.setOnClickListener(new OnClickListener() {

			@Override
			public void onLoadingViewClick(View view) {
				loadData(true);
			}
		});
		mLoadingView.showWaitView(R.string.loading_wait);
	}

	private void initListView() {
		mListview = findViewById(R.id.search_result_cardlist);
		mListview.setEmptyView(mLoadingView);
		mListview.needToRefreshOnFooter(true);
		mListview.needToRefreshOnHeader(false);
		mListview.setRefreshListener(this);
		mListview.setVisibility(View.GONE);

		mCardsAdapter = new CardArrayAdapter(this, mCardsArray);
		mCardsAdapter.setInnerViewTypeCount(100);
		mListview.setAdapter(mCardsAdapter);
	}

	private void loadData(boolean loadFirstPage) {
		int pageIndex = mPageIndex;
		if (loadFirstPage) {
			pageIndex = 1;
			mLoadingView.showWaitView(R.string.ptr1_loading_wait);
		}
		SearchNetEngine engine = new SearchNetEngine(mDataVersion, pageIndex, mkey);
		mNetTask = new NetTask(this, engine, 1);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		PageResult resultData = (PageResult) engine.getResultData();
		if (!resultData.isOK()) {
			if (mPageIndex == 1) {
				mLoadingView.showErrorView(R.string.load_failed_retry);
			}
		} else {
			List<com.jy.app.market.idata.card.Card> cards = resultData.getCards();
			if (cards == null || cards.size() == 0) {
				if (mLoadingView.getVisibility() == View.VISIBLE) {
					mLoadingView.showEmptyView(R.string.no_data);
					return;
				}
			} else {
				mDataVersion = resultData.getDataVersion();
				for (com.jy.app.market.idata.card.Card card : cards) {
					if (card instanceof CardApkImages) {
						Apk apk = ((CardApkImages) card).getApk();
						String title = apk.getTitle();
						title = title.replaceAll("<em>", "");
						title = title.replaceAll("</em>", "");
						apk.setTitle(title);
					}
					if (card instanceof CardApk) {
						Apk apk = ((CardApk) card).getApk();
						String title = apk.getTitle();
						title = title.replaceAll("<em>", "");
						title = title.replaceAll("</em>", "");
						apk.setTitle(title);
					}

					BaseUICard uiCard = CardsUtils.getCardInstance(this, card);
					if (uiCard == null) {
						continue;
					}
					uiCard.setIndex(mCardsArray.size());
					if (uiCard instanceof DownloadableUICard) {
						DownloadableUICard c = (DownloadableUICard) uiCard;
						c.setListView(mListview);
						addFileListener(c);
					}
					uiCard.setApkSource(new ApkSource("search", null, uiCard.getIndex(),
							mDataVersion, mkey, null, null));
					mCardsArray.add(uiCard);
				}
				mCardsAdapter.notifyDataSetChanged();
				mListview.footerRefreshingCompleted();
				mListview.setVisibility(View.VISIBLE);
				mLoadingView.setVisibility(View.GONE);
				mPageIndex++;
				if (mIsFooterRefresh) {
					mIsFooterRefresh = false;
				}

				if (resultData.getPageNo() >= resultData.getTotalPage()) {
					mListview.needToRefreshOnFooter(false);
				}
			}
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		if (mCardsAdapter.isEmpty()) {
			mListview.setVisibility(View.GONE);
			mLoadingView.showErrorView(R.string.ptrl_refresh_fail);
		} else {
			if (mIsFooterRefresh) {
				mListview.footerRefreshError();
				mIsFooterRefresh = false;
			}
		}
		Toast.makeText(this, R.string.network_error, Toast.LENGTH_SHORT).show();

	}

	@Override
	public void onTaskRunCanceled(int tag) {
		// nothing todo
	}

	@Override
	public void onHeaderRefreshing() {
		// no header refresh
	}

	@Override
	public void onFooterRefreshing() {
		mIsFooterRefresh = true;
		loadData(false);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.search_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case R.id.action_search_management:
			startSearch(mSearchEt.getText().toString().trim());
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId == EditorInfo.IME_ACTION_SEARCH) {
			startSearch(mSearchEt.getText().toString().trim());
			return true;
		}
		return false;
	}

	private void startSearch(String key) {
		if (TextUtils.isEmpty(key)) {
			Toast.makeText(this, R.string.please_input_search_keyword, Toast.LENGTH_SHORT).show();
			return;
		}
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mSearchEt.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		if (key.equals(mkey)) {
			return;
		}
		clearFileListener();
		mkey = key;
		mCardsAdapter.clear();
		mCardsAdapter.notifyDataSetChanged();
		loadData(true);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back_bn:
			finish();
			break;
		case R.id.clear_edit_view:
			mSearchEt.setText("");
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.showSoftInput(mSearchEt, InputMethodManager.HIDE_IMPLICIT_ONLY);
			break;
		default:
			break;
		}
	}
}
